<template>
	<view>
		<!-- 用户资料 -->
		<uni-popup ref="showVerify" type="center" border-radius="10px" background-color="#70552ddd">
			<view class="" style="width: 90vw;padding: 20px;">
				<view style="display: flex;flex-direction: column;align-items: center;margin-top: 10px;">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
						style="padding: 0;background-color: transparent;">
						<image :src="avatarUrl" mode="scaleToFill"
							style="width: 64px;height: 64px;border-radius: 50% 50%;"></image>
					</button>

					<view style="width: 100%;display: flex;justify-content: center;color: #fff;padding-bottom: 20px;">
						<input v-model="avatarNam" type="nickname" placeholder="点击授权用户昵称" @input="onChooseName"
							style="text-align: center;vertical-align:middle;" />
					</view>
				</view>

				<view>
					<tn-button shape="round" text-color="#70552d" bg-color="#f1f1f1" :disabled="isNotReg"
						@click="onRegeditUserinfo"
						:custom-style="{width:'100%',padding:'15px 0',fontSize:'large'}">更新个人信息</tn-button>
				</view>

				<view style="padding: 10px;display: flex;justify-content: center;color: #f3eacd;">
					<view @click="close">放弃登录</view>
				</view>
				
				<view class="" style="display: flex;flex-direction: column;gap: 5px;color: #f3eacd;padding: 15px 0;">
					<text>点击上方图标可以更换用户头像</text>
					<text>点击中间文本可以编辑用户昵称</text>
				</view>

			</view>
		</uni-popup>

	</view>
</template>

<script>
	import psMethod from '@/common/psMethod';
	import UniToCos from '@/js_sdk/com-ls-cos/components/ls-cos'

	export default {
		name: "person-verify-pop",
		data() {
			return {
				title: '用户资料',
				sConf: getApp().globalData,
				// 改资料
				agent: false,
				isNotReg: true,
				showSecret: false,
				avatarUrl: 'https://cos.yuejunxi.com/media/default/default_0.png',
				avatarNam: '新用户',
				curConcert: 0,
			};
		},

		methods: {
			open() {
				this.avatarUrl = 'https://cos.yuejunxi.com' + this.sConf.auth.face
				this.avatarNam = this.sConf.auth.nicename
				this.$refs.showVerify.open()
			},
			close() {
				this.$refs.showVerify.close()
			},
			/**
			 * 加载用户头像昵称
			 */
			onChooseAvatar(e) {
				console.log('onChooseAvatar', e);
				this.avatarUrl = e.detail.avatarUrl
				if (this.avatarUrl.includes('default/default') || !this.avatarNam || this.avatarNam.length === '新用户') {
					this.isNotReg = true
				} else {
					this.isNotReg = false
				}
			},
			/**
			 * 验证用户昵称
			 */
			onChooseName(e) {
				console.log('onChooseName', e);
				this.avatarNam = e.detail.value
				if (this.avatarUrl.includes('default/default') || !this.avatarNam || this.avatarNam.length === '新用户') {
					this.isNotReg = true
				} else {
					this.isNotReg = false
				}
			},
			/**
			 * 注册手机用户
			 */
			async onRegeditUserinfo() {
				console.log('onRegeditUserinfo');
				if (this.avatarUrl.includes('default/default')) {
					uni.showModal({
						title: '错误',
						content: '请点击头像图标授权',
						showCancel: false
					})
					return
				}
				if (this.avatarNam.length === 0 || this.avatarNam === '新用户') {
					uni.showModal({
						title: '错误',
						content: '请点击昵称授权',
						showCancel: false
					})
					return
				}

				let host = this.sConf.host + '/weapps/editBase/' + this.sConf.auth.id + '/'
				let token = this.sConf.token
				let data = {
					face: this.sConf.auth.face,
					nicename: this.avatarNam
				}
				if (this.avatarUrl !== 'https://cos.yuejunxi.com' + this.sConf.auth.face) {
					console.log('new face', this.avatarUrl, this.sConf.auth.face);
					let cosDict = await this.getUploadCos().then(res => {
						return res
					})
					console.log('image ->', cosDict);
					let images = await this.cosUploadFile(cosDict, this.avatarUrl)
					console.log('上传到cos ->', images);
					data['face'] = images
				}
				psMethod.authenticatorPatchSync(host, token, data).then(res => {
					console.log('手机登录成功', res);
					let prefix = this.sConf.run === 'trial' ? 'dev' : ''
					try {
						uni.setStorageSync(prefix + 'auth', res.resmsg);
					} catch (e) {
						console.log('写入本地缓存失败');
					}
					this.sConf.auth = res.resmsg
					this.$emit('reload')
					this.close()
				}).catch(err => {
					console.log('手机登录失败', err);
					uni.showModal({
						title: '更新失败',
						content: err.resmsg,
						showCancel: false
					})
				})
			},
			/**
			 * 上传图片
			 */
			getUploadCos() {
				console.log('加载cos参数');
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.sConf.host + '/api/cosSt/',
						method: 'POST',
						header: {
							'content-type': 'application/json',
							'authorization': this.sConf.token
						},
						data: {},
						success(res) {
							resolve(res.data.resmsg)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			cosUploadFile(cosDict, file) {
				// 传入bucket和region
				let cos = new UniToCos(cosDict.account.bucket, cosDict.account.region)
				// 传入secretId,secretKey,sessionToken
				cos.createCos(cosDict.credentials.tmpSecretId, cosDict.credentials.tmpSecretKey, cosDict.credentials
					.sessionToken)
				// 传入filePath和fileName
				let filePath = file;
				let fileName = 'media/face/' + this.sConf.auth.id + '.jpg';

				return new Promise((resolve, reject) => {
					cos.wxUploadFile(filePath, fileName).then(res => {
						console.log("上传图片", res.Location.substr(res.Location.indexOf('/')))
						resolve(res.Location.substr(res.Location.indexOf('/')))
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 同意用户协议
			 */
			eventAgree(e) {
				console.log('eventAgree', e);
				this.agent = true
				this.showSecret = false
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>